<template>
  <scroll class="suggest" 
    :data="result" 
    :pullup="pullup"
    @scrollToEnd="searchMore"
    ref="suggest"
    :beforeScroll="beforeScroll"
    @beforeScroll="listScroll"
  >
    <ul class="suggest-list">
      <li class="suggest-item" v-for="item in result" @click="selectItem(item)">
        <div class="icon">
          <i :class="getIconCls(item)"></i>
        </div>
        <div class="name">
          <p class="text" v-html="getDisplayName(item)"></p>
        </div>
      </li>
      <loading v-show="hasMore" title=""></loading>
    </ul>
    <div v-show="!hasMore && !result.length" class="no-result-wrapper">
      <no-result title="抱歉，暂无搜索结果"></no-result>
    </div>
  </scroll>
</template>

<script>
  import {search} from 'api/search'
  import {ERR_OK} from 'api/config'
  import {createSong} from 'common/js/song'
  import Scroll from 'base/scroll/scroll'
  import Loading from 'base/loading/loading'
  import Singer from 'common/js/singer'
  import {mapMutations, mapActions} from 'vuex'
  import NoResult from 'base/no-result/no-result'
  import {getSongVkey} from 'api/singer'

  const TYPE_SINGER = 'singer'
  const perpage = 20

  export default {
    props: {
      query: {
        type: String,
        default: ''
      },
      showSinger: {
        type: Boolean,
        default: true
      }
    },
    components: {
      Scroll,
      Loading,
      NoResult
    },
    watch: {
      query (newQuery) {
        this.search(newQuery)
      }
    },
    data () {
      return {
        page: 1,
        result: [],
        pullup: true,
        hasMore: true,
        beforeScroll: true
      }
    },
    methods: {
      search () {
        this.page = 1
        this.hasMore = true
        this.$refs.suggest.scrollTo(0, 0)                          // 重置滚动位置为0
        search(this.query, this.page, this.showSinger, perpage).then((res) => {
          if (res.code === ERR_OK) {
            this._genResult(res.data, (arr) => {
              this.result = arr
            })
            this._checkMore(res.data)
          }
        })
      },
      _checkMore (data) {               // 检测是否有更多
        const song = data.song
        if (!song.list.length || (song.curnum + song.curpage * perpage) > song.totalnum) {    // 当前取到的值 + 之前取到的值 和 总数作比较
          this.hasMore = false
        }
      },
      searchMore () {
        if (!this.hasMore) {
          return
        }
        this.page++
        search(this.query, this.page, this.showSinger, perpage).then((res) => {
          if (res.code === ERR_OK) {
            // this.result = this.result.concat(this._genResult(res.data))
            this._genResult(res.data, (arr) => {
              this.result = this.result.concat(arr)
            })
            this._checkMore(res.data)
          }
        })
      },
      _genResult (data, callback) {
        let ret = []
        if (data.zhida && data.zhida.singerid) {
          ret.push({...data.zhida, ...{type: TYPE_SINGER}})    // 把两个对象扩展运算符，添加到一个对象上
        }
        if (data.song) {
          // ret = ret.concat(this._normalizeSongs(data.song.list))
          this._normalizeSongs(data.song.list, (arr) => {
            ret = ret.concat(arr)
            callback(ret)
          })
        }
      },
      _normalizeSongs (list, callback) {
        let ret = []
        list.forEach((item) => {
          const musicData = item
          getSongVkey(musicData.songmid).then((res) => {
            const vkey = res.data.items[0].vkey
            if (musicData.songid && musicData.albummid) {
              ret.push(createSong(musicData, vkey))
            }
          })
        })
        let timeout = function () {
          if (ret.length === list.length) {
            callback(ret)
          } else {
            setTimeout(() => {
              timeout()
            }, 200)
          }
        }
        timeout()
      },
      getIconCls (item) {
        if (item.type === TYPE_SINGER) {
          return 'icon-mine'
        } else {
          return 'icon-music'
        }
      },
      getDisplayName (item) {
        if (item.type === TYPE_SINGER) {
          return item.singername
        } else {
          return `${item.name}-${item.singer}`
        }
      },
      selectItem (item) {
        if (item.type === TYPE_SINGER) {
          const singer = new Singer({
            id: item.singermid,
            name: item.singername
          })
          this.$router.push({
            path: `/search/${singer.id}`
          })
          this.setSinger(singer)                              // 之前是通过修改mutations里面的singer来传递数据，修改了singer的数据
        } else {
          this.insertSong(item)                               // 这里需要修改多个state里面的状态。所以使用mapActions做一个封装
        }
        this.$emit('select', item)
      },
      ...mapMutations({
        setSinger: 'SET_SINGER'
      }),
      ...mapActions([
        'insertSong'
      ]),
      listScroll () {
        this.$emit('listScroll')
      },
      refresh () {
        this.$refs.suggest.refresh()
      }
    }
  }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "~common/stylus/variable"
  @import "~common/stylus/mixin"

  .suggest
    height: 100%
    overflow: hidden
    .suggest-list
      padding: 0 30px
      .suggest-item
        display: flex
        align-items: center
        padding-bottom: 20px
      .icon
        flex: 0 0 30px
        width: 30px
        [class^="icon-"]
          font-size: 14px
          color: $color-text-d
      .name
        flex: 1
        font-size: $font-size-medium
        color: $color-text-d
        overflow: hidden
        .text
          no-wrap()
    .no-result-wrapper
      position: absolute
      width: 100%
      top: 50%
      transform: translateY(-50%)
</style>